package com.rock.code.province.hn.coll;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.rock.code.common.util.*;
import com.rock.code.datacollconfig.coll.interfaces.CollDataItemInterface;
import com.rock.code.datacollconfig.zabbix.dao.TbCollResConfDao;
import com.rock.code.datacollconfig.zabbix.dao.TbCollResConfDetailDao;
import com.rock.code.datacollconfig.zabbix.domain.TbCollResConf;
import com.rock.code.datacollconfig.zabbix.domain.TbCollResConfDetail;
import com.rock.code.datacollconfig.zabbix.service.TbCollResConfService;
import org.apache.commons.lang.StringUtils;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author zhangli
 * @version V1.0
 * @create 2019-02-27 15:20
 **/
public class ZabbixCollImpl implements CollDataItemInterface {
    @Resource
    TbCollResConfService tbCollResConfServiceImpl;

    @Resource
    TbCollResConfDao tbCollResConfDao;

    @Resource
    TbCollResConfDetailDao tbCollResConfDetailDao;

    @Override
    public void execute(String[] args) throws Exception {
//        tbCollResConfServiceImpl = (TbCollConfSnmpService) SpringContextUtil.getBeanByClass(TbCollResConfServiceImpl.class);

        if(args.length<3){
            return;
        }
        String  startID = args[3].split(",")[0];
        String  endID = args[3].split(",")[1];

        String sql1 = "select f.id,\n" +
                "       f.coll_type,\n" +
                "       f.coll_type,\n" +
                "       f.resource_name,\n" +
                "       f.ip,\n" +
                "       f.path,\n" +
                "       l.kpi_rule,\n" +
                "       l.kpi_name,\n" +
                "       l.kpi_id\n" +
                "  from tb_coll_resource_conf f, tb_coll_resource_kpi_detail l\n" +
                " where f.resource_type = l.resource_type\n" +
                "   and f.enable = l.enable\n" +
                "   and f.enable = 1\n" +
                "   and f.id between "+startID+" and "+endID;
//        String sql2 = "s";
        tbCollResConfDao = (TbCollResConfDao) SpringContextUtil.getBeanByClass(TbCollResConfDao.class);
        tbCollResConfDetailDao = (TbCollResConfDetailDao) SpringContextUtil.getBeanByClass(TbCollResConfDetailDao.class);

        List<TbCollResConfDetail> _detailList = tbCollResConfDetailDao.getAllCollResConfDetail(null);
        Map<String, String> _map = new HashMap<>();
        _map.put("startID", startID);
        _map.put("endID", endID);
//        List<TbCollResConf> _list = tbCollResConfDao.getAllCollResConf(_map);
        List<TbCollResConf> _list = tbCollResConfDao.queryCustomDataBySql(_map);

        try {
            //kpi 指标 放入缓存
            HashMap<String, List<TbCollResConfDetail>> cacheMap = new HashMap<>();
            for (TbCollResConfDetail tbCollResConfDetail : _detailList) {
                String resourceType = tbCollResConfDetail.getResource_type();
                if (cacheMap.get(resourceType) != null && !cacheMap.isEmpty()) {
                    List<TbCollResConfDetail> detailList = cacheMap.get(resourceType);
                    detailList.add(tbCollResConfDetail);
                } else {
                    List<TbCollResConfDetail> detailList = new ArrayList<>();
                    detailList.add(tbCollResConfDetail);
                    cacheMap.put(tbCollResConfDetail.getResource_type(), detailList);
                }

            }

            List hostList = ZabbixUtil.getHost();

            for (TbCollResConf tbCollResConf : _list) {
                try {
                    String resourceType = tbCollResConf.getResource_type();
                    String ip = tbCollResConf.getIp();
                    String hsotId = getHostId(hostList, ip);
                    if (hsotId == null) {
                        continue;
                    }

                    String kbp = tbCollResConf.getKbp();
                    String path = tbCollResConf.getPath();
                    List<TbCollResConfDetail> detaiList = cacheMap.get(resourceType);

                    doZabbix(tbCollResConf, hsotId, detaiList);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }


    }

    private String getHostId(List hostList, String ip) {
        for (Object obj : hostList) {
            HashMap map = (HashMap) obj;
            String hostId = String.valueOf(map.get(ip));
            if (!hostId.equals("null") && hostId != null) {
                return hostId;
            }

        }
        return null;
    }

    private void doZabbix(TbCollResConf tbCollResConf, String hostId, List<TbCollResConfDetail> detaiList) {
        if (detaiList == null || detaiList.isEmpty()) {
            return;
        }
        WriteKPI writeKPI = new WriteKPI();
        String dataTime = writeKPI.getNowTime();
        String ip = tbCollResConf.getIp();
        String kbp = tbCollResConf.getKbp();
        String path = tbCollResConf.getPath();

        JSONArray jsonArray = ZabbixUtil.getZabbixItemForHostId(hostId);
        String uname = ZabbixUtil.getHostType(hostId);
        for (Object obj : jsonArray) {
            JSONObject _json = (JSONObject) obj;
            String key = _json.getString("key_");
            for (TbCollResConfDetail tbCollResConfDetail : detaiList) {
                tbCollResConfDetail.setEnable("1");
                String kpi_id = tbCollResConfDetail.getKpi_id();//kpi_id
                String key_ = tbCollResConfDetail.getKpi_rule();// zabbix key_
                String _kbp_id = tbCollResConfDetail.getKbp_id();
                String resourceType = tbCollResConfDetail.getResource_type();

                Map<String, String> value = null;
                // 指标格式化
                if ("Linux".equals(uname.split(" ")[0])) {
                    value = FormatValue.formatLinuxValue(key, key_, _json, kpi_id);
                }
                if ("Windows".equals(uname.split(" ")[0])) {
                    value = FormatValue.formatWindowsValue(key, key_, _json, kpi_id);
                }
                if ("HP-UX".equals(uname.split(" ")[0])) {
                    value = FormatValue.formatHpValue(key, key_, _json, kpi_id);
                }
                if ("AIX".equals(uname.split(" ")[0])) {
                    value = FormatValue.formatAIXValue(key, key_, _json, kpi_id);
                }

                String kpi_value = value == null ? null : value.get("kpi_value");
                String entity_id = value == null ? null : value.get("entity_id");

                // 系统文件与磁盘使用率kbp后缀要求是文件系统或者磁盘实体，这里根据采集指标自动获取。
                String kbp_id = "";
                if (entity_id != null) {
                    kbp_id = kbp + _kbp_id
                            + ":" + ip.replace(".", "_")
                            + "-" + entity_id;
                } else {
                    kbp_id = kbp + _kbp_id
                            + ":" + ip.replace(".", "_")
                            + "-" + tbCollResConfDetail.getEntity_id();
                }

                if (!StringUtils.isBlank(kpi_value)) {
                    writeKPI.writeKPItoList(kpi_value, kpi_id, kbp_id, dataTime, resourceType);
                }
            }
        }

        WriteFile wf = new WriteFile();
        wf.writeSevenStrucFile(path, writeKPI.getVECTOR());
    }
}
